library dynamicDLL;

uses
  SysUtils,
  Math,
  ulkJSON in 'ulkJSON.pas';

type
  item = record
    name : string[50];
    weight : integer;
    price : integer;
    taken : boolean;
    func: real;
  end;

var
  items : Array of item;
  ans: array [0..50] of boolean;
  size : Integer;
  i,w,j, currweight, currprice : integer;
  js:TlkJSONobject;
  f : Text;
  jsn : String;
  s : String;
  var dp: array of array of integer;
  maxprice:integer;

procedure pack(size:integer; input:PChar; output:Pchar); stdcall;
begin
  // get stupid JSON
  assignfile(f, String(input));
  reset(f);
  jsn:= '{"items":';
  while not eof(f) do
  begin
    readln(f, s);
    jsn:=jsn+s;
  end;
  jsn:=jsn+'}';
  js := TlkJSON.ParseText(jsn) as TlkJSONobject;

  // parse stupid JSON
  for i := 0 to (js.Field['items'] as TlkJSONList).count - 1 do
  begin
    setlength(items, length(items)+1);
    items[i].name := ((js.Field['items'] as TlkJSONList).child[i] as TlkJSONobject).getstring('name');
    items[i].weight := strtoint(((js.Field['items'] as TlkJSONList).child[i] as TlkJSONobject).field['weight'].value);
    items[i].price := strtoint(((js.Field['items'] as TlkJSONList).child[i] as TlkJSONobject).field['price'].value);
    items[i].func := -1;
    items[i].taken := false;
  end;
  js.Free;

  setlength(dp, size+1);
  for i:=0 to size do
    setlength(dp[i], length(items)+1);

for w:=1 to size do
  for j:=1 to length(items) do
    begin
      if items[j-1].weight <= w then
      begin
        dp[w][j] := max(dp[w][j-1], dp[w-items[j-1].weight][j-1]+items[j-1].price);
      end
      else
        dp[w][j] := dp[w][j-1];
    end;

    i:= size;
    j := length(items);
    while (dp[i][j] <> 0) do
    begin
      while (dp[i][j-1] = dp[i][j]) do
        j := j - 1;
      items[j-1].taken := true;
      i := i - items[j-1].weight;
      j := j - 1;
    end;

  assignfile(f, String(output));
  rewrite(f);
  s:='['+#13#10;
  for i:=0 to length(items)-1 do
    if items[i].taken then
    begin
      s:=s+'{"name": "'+items[i].name+'", ';
      s:=s+'"weight": '+inttostr(items[i].weight) + ', ';
      if i<>length(items)-1 then
        s:=s+'"price": '+inttostr(items[i].price) + '},'+#13#10
      else
        s:=s+'"price": '+inttostr(items[i].price) + '}'+#13#10
    end;
  s:=s+']';
  write(f, s);
  closefile(f); 
end;

exports pack;

begin
end.
